
#include "InvoiceDialog.h"
#include "InvoiceItemDialog.h"
#include "InvoiceItemDelegate.h"
#include "InvoiceItemModel.h"
#include "InvoicePrinter.h"
#include "Helper.h"

#include <QMessageBox>
#include <QFileDialog>
#include <QDesktopServices>
#include <QUrl>
#include <QDir>

using namespace ecocity;

static const QString all_proveiders = "Todos";

//---------------------------------------------------------------

InvoiceDialog::InvoiceDialog( const Customer& customer,
                              const std::vector< Product >& products,
                              QWidget *parent )
    : QDialog( parent ),
      m_customer( customer ),
      m_products( products ),
      m_invoice( QDate::currentDate(), customer ),
      // Set up model
      m_invoice_items_model( m_invoice.items( ) )
{
    setupUi( this );

    setWindowTitle( "Factura" );

    // Set up view
    items_view->setModel( &m_invoice_items_model );

    items_view->setItemDelegate( new InvoiceItemDelegate( this ) );

    // Set up Customer view details
    QStringList customer_details;
    customer_details << customer.name()
                     << customer.nif()
                     << customer.address()
                     << QString( "Telf: %1").arg( customer.phone() );

    customer_label->setText( customer_details.join( "\n" ) );

    items_view->resizeColumnsToContents( );
    items_view->horizontalHeader()->setStretchLastSection( true );

    sum_sumary->clear( );
    taxes_summary->clear( );

    connect( finnish_button, SIGNAL( accepted() ),
             this, SLOT( accept() ) );

    connect( finnish_button, SIGNAL( rejected() ),
             this, SLOT( reject() ) );

    connect( add_invoice_item, SIGNAL( clicked() ),
             this, SLOT( on_add_invoice_item() ) );

    connect( &m_invoice_items_model, SIGNAL( model_changed() ),
             this, SLOT( model_changed( ) ) );
}

//---------------------------------------------------------------

void
InvoiceDialog::model_changed( )
{
    items_view->hideColumn( InvoiceItemsModel::ITEM_PRICE_TYPE );
    //items_view->hideColumn( InvoiceItemsModel::ITEM_UNIQUE_ID );
}

//---------------------------------------------------------------

Invoice
InvoiceDialog::get_invoice( ) const
{
    return m_invoice;
}

//---------------------------------------------------------------

std::vector< InvoiceItem >
InvoiceDialog::get_invoice_items( ) const
{
    return m_invoice.items( );
}

//---------------------------------------------------------------

void
InvoiceDialog::accept( )
{
    if ( m_invoice.items().size() == 0 )
    {
        QMessageBox::warning( this, "Invoice is empty", "Invoice is empty" );
        return;
    }

    QDialog::accept();
}

//---------------------------------------------------------------

void
InvoiceDialog::on_add_invoice_item( )
{
    InvoiceItemDialog item_dialog( m_customer.type( ),
                                   m_products, this );

    if ( item_dialog.exec() == QDialog::Rejected )
    {
        return;
    }

    InvoiceItem item = item_dialog.get_item( );

    if ( item.quantity() == 0 )
    {
        return;
    }

    m_invoice.add_item( item );
    m_invoice_items_model.reset( m_invoice.items( ) );

    update_summary( );
}

//---------------------------------------------------------------

void
InvoiceDialog::update_summary( )
{
    taxes_summary->setText( InvoicePrinter::taxes_summary( m_invoice ) );

    sum_sumary->setText( InvoicePrinter::final_summary( m_invoice ) );
}

//---------------------------------------------------------------

void
ecocity::InvoiceDialog::on_delete_item_clicked()
{
    QItemSelectionModel* model = items_view->selectionModel( );

    if ( !model->hasSelection( ) )
    {
        QMessageBox::warning( this, "Elemento en factura no seleccionado",
                                    "Seleciona un elemento en la factura" );
        return;
    }

    QModelIndex proxy_index = items_view->currentIndex( );
    const InvoiceItem* item = m_invoice_items_model.invoice_item( proxy_index );

    if ( !proxy_index.isValid( )
         || !item )
    {
        QMessageBox::warning( this, "InvoiceDialog Index not found",
                                    "Product Index not found" );
        return;
    }

    if ( QMessageBox::question(
             this,
             QString( "Eliminar %1 %2 ?" ).arg( QString::number( item->quantity() ), item->product().name( ) ),
             QString( "Eliminar %1 %2 ?" ).arg( QString::number( item->quantity() ), item->product().name( ) ),
             QMessageBox::Yes, QMessageBox::No ) == QMessageBox::Yes )
    {
        m_invoice.remove_item( item->product().name(), item->quantity(), item->weight() );

        m_invoice_items_model.reset( m_invoice.items( ) );

        update_summary( );
    }
}

//---------------------------------------------------------------

void
ecocity::InvoiceDialog::on_export_invoice_clicked( )
{
    QString default_file = QDir::currentPath( );
    default_file.append( "/exported_invoices/" );
    default_file.append( m_invoice.date().toString( QString( "ddMMyyyy_" ) ) );
    default_file.append( m_invoice.customer().name() );
    default_file.append( ".txt" );

    QString file = QFileDialog::getSaveFileName( this, tr( "Guardar factura"),
                                default_file, tr( "Text ( *.txt *.odt )" ) );

    if( file.isEmpty( ) )
    {
        return;
    }

    bool ok = InvoicePrinter::print( file, m_invoice );

    if ( !ok )
    {
        QMessageBox::warning( this, "Exportar factura ha fallado",
                              "Exportar factura ha fallado" );
        return;
    }

    QString file_path = QString( "file://%1" ).arg( file );

    QDesktopServices::openUrl( QUrl( file_path ) );
}
